import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Users,
  TrendingUp,
  Target,
  Heart,
  Trash2,
  RefreshCw,
  Copy,
  Clock,
  Star,
  Tag,
  MessageCircle,
  BarChart3,
  Eye,
  X,
} from 'lucide-react';
import { userPersonaApi, aiProviderApi } from '../api';
import type {
  UserPersonaAnalysisRequest,
  UserPersonaAnalysisResponse,
  UserPersonaHistory,
  UserPersonaStats,
  UserPersona,
  InterestTopic,
  AIProvider,
} from '../api/types';
import { useApiError } from '../hooks/useApiError';

const UserPersonaAnalysis: React.FC = () => {
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [analysisResult, setAnalysisResult] = useState<UserPersonaAnalysisResponse | null>(null);
  const [history, setHistory] = useState<UserPersonaHistory[]>([]);
  const [stats, setStats] = useState<UserPersonaStats | null>(null);
  const [activeTab, setActiveTab] = useState<'analyze' | 'history'>('analyze');

  // AI Provider and Model state
  const [providers, setProviders] = useState<AIProvider[]>([]);
  const [availableModels, setAvailableModels] = useState<string[]>([]);
  const [loadingModels, setLoadingModels] = useState(false);

  // Form state
  const [formData, setFormData] = useState<UserPersonaAnalysisRequest>({
    product_name: '',
    selling_points: '',
    product_category: '',
    price_range: '',
    target_market: '',
    additional_info: '',
  });

  // Filters
  const [historyFilter, setHistoryFilter] = useState({
    search: '',
    category: '',
  });

  // Pagination
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const itemsPerPage = 20;

  // Detail modal state
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedHistoryItem, setSelectedHistoryItem] = useState<UserPersonaHistory | null>(null);
  const [loadingDetail, setLoadingDetail] = useState(false);

  const { handleError } = useApiError();

  // 添加请求去重机制
  const pendingRequests = useRef(new Set<string>());
  const requestCache = useRef(new Map<string, { data: unknown; timestamp: number }>());
  const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

  // 通用请求去重函数
  const makeRequestWithDeduplication = useCallback(
    async <T,>(
      requestKey: string,
      requestFn: () => Promise<T>,
      useCache = true
    ): Promise<T | null> => {
      // 检查是否有正在进行的相同请求
      if (pendingRequests.current.has(requestKey)) {
        return null;
      }

      // 检查缓存
      if (useCache) {
        const cached = requestCache.current.get(requestKey);
        if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
          return cached.data as T;
        }
      }

      // 添加到待处理请求集合
      pendingRequests.current.add(requestKey);

      try {
        const result = await requestFn();

        // 缓存结果
        if (useCache) {
          requestCache.current.set(requestKey, {
            data: result,
            timestamp: Date.now(),
          });
        }

        return result;
      } finally {
        // 移除待处理请求标记
        pendingRequests.current.delete(requestKey);
      }
    },
    [CACHE_DURATION]
  );

  // Fetch AI providers - 添加去重和缓存
  const fetchProviders = useCallback(async () => {
    try {
      const response = await makeRequestWithDeduplication('ai-providers', () =>
        aiProviderApi.getProviders()
      );

      if (response) {
        const activeProviders =
          response.rows?.filter(
            (provider: AIProvider) => provider.is_active && provider.status === 'active'
          ) || [];
        setProviders(activeProviders);
      }
    } catch (error) {
      handleError(error, '获取AI服务提供商失败');
    }
  }, [handleError, makeRequestWithDeduplication]);

  // Fetch available models for selected provider
  const fetchAvailableModels = useCallback(
    async (providerId: number) => {
      console.log('Starting to fetch models for provider:', providerId);
      setLoadingModels(true);
      try {
        const response = await aiProviderApi.getProviderModels(providerId);
        console.log('API response for models:', response);

        // 处理不同的响应格式
        let models: string[] = [];
        if (Array.isArray(response)) {
          // 直接是数组
          models = response;
        } else if (
          response &&
          typeof response === 'object' &&
          'models' in response &&
          Array.isArray((response as { models: string[] }).models)
        ) {
          // 包含 models 字段的对象
          models = (response as { models: string[] }).models;
        } else if (
          response &&
          typeof response === 'object' &&
          'data' in response &&
          Array.isArray((response as { data: string[] }).data)
        ) {
          // 包含 data 字段的对象（后端标准响应格式）
          models = (response as { data: string[] }).data;
        } else if (response && typeof response === 'object' && 'data' in response) {
          // 标准后端响应格式：{ code, data, msg }
          models = ((response as { data: string[] }).data as string[]) || [];
        }

        console.log('Processed models:', models);
        setAvailableModels(models);
      } catch (error) {
        console.error('获取模型列表失败:', error);
        handleError(error, '获取模型列表失败');
        setAvailableModels([]);
      } finally {
        setLoadingModels(false);
      }
    },
    [handleError]
  );

  // Fetch history - 优化依赖项
  const fetchHistory = useCallback(
    async (page = 1) => {
      try {
        const params = new URLSearchParams({
          page: page.toString(),
          limit: itemsPerPage.toString(),
          ...(historyFilter.category && { category: historyFilter.category }),
        });

        const response = await userPersonaApi.getHistory(`?${params}`);
        setHistory(response.rows || []);

        const totalCount = response.count || 0;
        setTotalItems(totalCount);
        setTotalPages(Math.ceil(totalCount / itemsPerPage));
        setCurrentPage(page);
      } catch (error) {
        handleError(error, '获取历史记录失败');
      }
    },
    [historyFilter.category, handleError]
  );

  // Fetch stats - 添加去重和缓存
  const fetchStats = useCallback(async () => {
    try {
      const response = await makeRequestWithDeduplication(
        'user-persona-stats',
        () => userPersonaApi.getStats(),
        false // 统计数据不使用长时间缓存
      );

      if (response) {
        setStats(response);
      }
    } catch (error) {
      handleError(error, '获取统计数据失败');
    }
  }, [handleError, makeRequestWithDeduplication]);

  // Initialize data - 使用空依赖数组，只在组件挂载时执行一次
  useEffect(() => {
    // Capture current refs at the time the effect runs
    const currentPendingRequests = pendingRequests.current;
    const currentRequestCache = requestCache.current;

    const initializeData = async () => {
      await fetchProviders();
      await fetchStats();

      // 如果已经选择了提供商，自动加载其模型
      if (formData.provider_id) {
        fetchAvailableModels(formData.provider_id);
      }
    };

    initializeData();

    // 清理函数：组件卸载时清理待处理的请求和缓存
    return () => {
      currentPendingRequests.clear();
      currentRequestCache.clear();
    };
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Fetch history when tab changes or filters change - 优化依赖项
  useEffect(() => {
    if (activeTab === 'history') {
      fetchHistory(1);
    }
  }, [activeTab, historyFilter.category]); // eslint-disable-line react-hooks/exhaustive-deps

  // Handle form input change
  const handleInputChange = (field: keyof UserPersonaAnalysisRequest, value: string | number) => {
    setFormData(prev => ({
      ...prev,
      [field]: value,
    }));

    // Fetch models when provider changes
    if (field === 'provider_id') {
      const providerId = typeof value === 'number' ? value : parseInt(value.toString());
      if (providerId && !isNaN(providerId)) {
        console.log('Fetching models for provider:', providerId);
        fetchAvailableModels(providerId);
      } else {
        // Clear models if no provider selected
        setAvailableModels([]);
      }
    }
  };

  // Handle analysis
  const handleAnalyze = async () => {
    if (!formData.product_name.trim() || !formData.selling_points.trim()) {
      alert('产品名称和卖点不能为空');
      return;
    }

    setIsAnalyzing(true);
    try {
      const response = await userPersonaApi.analyze(formData);
      setAnalysisResult(response);

      // Refresh stats
      fetchStats();

      // Switch to analysis result display
      setActiveTab('analyze');
    } catch (error) {
      handleError(error, '用户画像分析失败');
    } finally {
      setIsAnalyzing(false);
    }
  };

  // Handle copy to clipboard
  const handleCopy = (text: string) => {
    navigator.clipboard.writeText(text);
    // You can add a toast notification here
  };

  // Handle delete history item
  const handleDeleteHistory = async (id: string) => {
    if (!confirm('确定要删除这条记录吗？')) {
      return;
    }

    try {
      await userPersonaApi.deleteHistory(id);
      fetchHistory(currentPage);
      fetchStats();
    } catch (error) {
      handleError(error, '删除失败');
    }
  };

  // Handle toggle favorite
  const handleToggleFavorite = async (id: string) => {
    try {
      await userPersonaApi.toggleFavorite(id);
      fetchHistory(currentPage);
    } catch (error) {
      handleError(error, '操作失败');
    }
  };

  // Handle view detail
  const handleViewDetail = async (id: string) => {
    setLoadingDetail(true);
    try {
      const item = await userPersonaApi.getHistoryItem(id);
      setSelectedHistoryItem(item);
      setShowDetailModal(true);
    } catch (error) {
      handleError(error, '获取详情失败');
    } finally {
      setLoadingDetail(false);
    }
  };

  // Handle close detail modal
  const handleCloseDetailModal = () => {
    setShowDetailModal(false);
    setSelectedHistoryItem(null);
  };

  // Handle keyboard events for modal
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && showDetailModal) {
        handleCloseDetailModal();
      }
    };

    if (showDetailModal) {
      document.addEventListener('keydown', handleKeyDown);
      return () => {
        document.removeEventListener('keydown', handleKeyDown);
      };
    }
  }, [showDetailModal]);

  // Render persona card
  const renderPersonaCard = (persona: UserPersona, isPrimary = true) => (
    <div
      key={persona.id}
      className={`border rounded-lg p-4 ${isPrimary ? 'bg-blue-50 border-blue-200' : 'bg-gray-50 border-gray-200'}`}
    >
      <div className="flex items-center justify-between mb-3">
        <h4 className="font-semibold text-gray-900">{persona.name}</h4>
        <div className="flex items-center space-x-2">
          <span
            className={`px-2 py-1 rounded-full text-xs font-medium ${isPrimary ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800'}`}
          >
            {isPrimary ? '主要用户' : '潜在用户'}
          </span>
          <div className="flex items-center">
            <Star className="h-4 w-4 text-yellow-400 mr-1" />
            <span className="text-sm text-gray-600">{(persona.confidence * 100).toFixed(0)}%</span>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 text-sm">
        <div>
          <span className="font-medium text-gray-700">年龄:</span>
          <span className="ml-1 text-gray-600">{persona.age}</span>
        </div>
        <div>
          <span className="font-medium text-gray-700">职业:</span>
          <span className="ml-1 text-gray-600">{persona.occupation}</span>
        </div>
        {persona.income && (
          <div>
            <span className="font-medium text-gray-700">收入:</span>
            <span className="ml-1 text-gray-600">{persona.income}</span>
          </div>
        )}
        {persona.education && (
          <div>
            <span className="font-medium text-gray-700">学历:</span>
            <span className="ml-1 text-gray-600">{persona.education}</span>
          </div>
        )}
      </div>

      <div className="mt-4">
        <p className="text-sm text-gray-700 mb-2">
          <span className="font-medium">生活方式:</span> {persona.lifestyle}
        </p>
      </div>

      <div className="mt-4 space-y-2">
        {persona.pain_points && persona.pain_points.length > 0 && (
          <div>
            <span className="text-sm font-medium text-red-700">痛点:</span>
            <div className="flex flex-wrap gap-1 mt-1">
              {persona.pain_points.map((point, idx) => (
                <span key={idx} className="px-2 py-1 bg-red-100 text-red-800 text-xs rounded">
                  {point}
                </span>
              ))}
            </div>
          </div>
        )}

        {persona.motivations && persona.motivations.length > 0 && (
          <div>
            <span className="text-sm font-medium text-green-700">动机:</span>
            <div className="flex flex-wrap gap-1 mt-1">
              {persona.motivations.map((motivation, idx) => (
                <span key={idx} className="px-2 py-1 bg-green-100 text-green-800 text-xs rounded">
                  {motivation}
                </span>
              ))}
            </div>
          </div>
        )}

        {persona.behaviors && persona.behaviors.length > 0 && (
          <div>
            <span className="text-sm font-medium text-blue-700">行为特征:</span>
            <div className="flex flex-wrap gap-1 mt-1">
              {persona.behaviors.map((behavior, idx) => (
                <span key={idx} className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded">
                  {behavior}
                </span>
              ))}
            </div>
          </div>
        )}

        {persona.preferences && persona.preferences.length > 0 && (
          <div>
            <span className="text-sm font-medium text-purple-700">偏好:</span>
            <div className="flex flex-wrap gap-1 mt-1">
              {persona.preferences.map((preference, idx) => (
                <span key={idx} className="px-2 py-1 bg-purple-100 text-purple-800 text-xs rounded">
                  {preference}
                </span>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );

  // Render interest topics
  const renderInterestTopics = (topics: InterestTopic[]) => (
    <div className="space-y-4">
      {topics.map((topic, idx) => (
        <div key={idx} className="border rounded-lg p-4">
          <div className="flex items-center justify-between mb-3">
            <h4 className="font-semibold text-gray-900 flex items-center">
              <Tag className="h-4 w-4 mr-2" />
              {topic.category}
            </h4>
            <div className="flex items-center">
              <Star className="h-4 w-4 text-yellow-400 mr-1" />
              <span className="text-sm text-gray-600">
                {(topic.relevance * 100).toFixed(0)}% 相关
              </span>
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            {topic.topics.map((topicName, topicIdx) => (
              <span
                key={topicIdx}
                className="px-3 py-1 bg-indigo-100 text-indigo-800 text-sm rounded-full"
              >
                {topicName}
              </span>
            ))}
          </div>
        </div>
      ))}
    </div>
  );

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-900">用户画像分析</h1>
        <div className="flex items-center space-x-4">
          {stats && (
            <div className="text-sm text-gray-600">
              今日分析: {stats.today_analyses} | 本周: {stats.week_analyses} | 总计:{' '}
              {stats.total_analyses}
            </div>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="border-b border-gray-200">
        <nav className="-mb-px flex space-x-8">
          <button
            onClick={() => setActiveTab('analyze')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'analyze'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            <div className="flex items-center">
              <Users className="h-4 w-4 mr-2" />
              用户画像分析
            </div>
          </button>
          <button
            onClick={() => setActiveTab('history')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'history'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            <div className="flex items-center">
              <Clock className="h-4 w-4 mr-2" />
              历史记录
            </div>
          </button>
        </nav>
      </div>

      {/* Generate Tab */}
      {activeTab === 'analyze' && (
        <div className="space-y-6">
          {/* Form */}
          <div className="bg-white rounded-lg shadow p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">产品信息</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">产品名称 *</label>
                <input
                  type="text"
                  value={formData.product_name}
                  onChange={e => handleInputChange('product_name', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-900 placeholder-gray-500"
                  placeholder="请输入产品名称"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">产品类别</label>
                <select
                  value={formData.product_category}
                  onChange={e => handleInputChange('product_category', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-900"
                >
                  <option value="">选择产品类别</option>
                  <option value="数码电子">数码电子</option>
                  <option value="服装配饰">服装配饰</option>
                  <option value="家居用品">家居用品</option>
                  <option value="美妆护理">美妆护理</option>
                  <option value="食品饮料">食品饮料</option>
                  <option value="运动健身">运动健身</option>
                  <option value="汽车用品">汽车用品</option>
                  <option value="母婴用品">母婴用品</option>
                  <option value="图书文具">图书文具</option>
                  <option value="软件服务">软件服务</option>
                  <option value="其他">其他</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">价格区间</label>
                <select
                  value={formData.price_range}
                  onChange={e => handleInputChange('price_range', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-900"
                >
                  <option value="">选择价格区间</option>
                  <option value="100元以下">100元以下</option>
                  <option value="100-500元">100-500元</option>
                  <option value="500-1000元">500-1000元</option>
                  <option value="1000-5000元">1000-5000元</option>
                  <option value="5000元以上">5000元以上</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">目标市场</label>
                <input
                  type="text"
                  value={formData.target_market}
                  onChange={e => handleInputChange('target_market', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-900 placeholder-gray-500"
                  placeholder="如：国内一线城市、年轻人群体等"
                />
              </div>
            </div>

            <div className="mt-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">产品卖点 *</label>
              <textarea
                value={formData.selling_points}
                onChange={e => handleInputChange('selling_points', e.target.value)}
                rows={4}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-900 placeholder-gray-500"
                placeholder="请详细描述产品的主要卖点、特色功能、优势等..."
              />
            </div>

            <div className="mt-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">附加信息</label>
              <textarea
                value={formData.additional_info}
                onChange={e => handleInputChange('additional_info', e.target.value)}
                rows={3}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-900 placeholder-gray-500"
                placeholder="其他需要考虑的信息，如品牌背景、市场竞争情况等..."
              />
            </div>

            {/* AI Provider Selection */}
            {providers.length > 0 && (
              <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    AI服务提供商
                  </label>
                  <select
                    value={formData.provider_id || ''}
                    onChange={e =>
                      handleInputChange(
                        'provider_id',
                        e.target.value ? parseInt(e.target.value) : ''
                      )
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-900"
                  >
                    <option value="">使用默认提供商</option>
                    {providers.map(provider => (
                      <option key={provider.id} value={provider.id}>
                        {provider.name} ({provider.provider_type})
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">模型选择</label>
                  <select
                    value={formData.model || ''}
                    onChange={e => handleInputChange('model', e.target.value)}
                    disabled={!formData.provider_id || loadingModels}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 text-gray-900"
                  >
                    <option value="">使用默认模型</option>
                    {availableModels.map(model => (
                      <option key={model} value={model}>
                        {model}
                      </option>
                    ))}
                  </select>
                  {loadingModels && <p className="text-sm text-gray-500 mt-1">加载模型列表中...</p>}
                  {!formData.provider_id && (
                    <p className="text-sm text-gray-500 mt-1">请先选择AI服务提供商</p>
                  )}
                  {formData.provider_id && !loadingModels && availableModels.length === 0 && (
                    <p className="text-sm text-yellow-600 mt-1">该提供商没有可用模型或加载失败</p>
                  )}
                  {formData.provider_id && !loadingModels && availableModels.length > 0 && (
                    <p className="text-sm text-green-600 mt-1">
                      已加载 {availableModels.length} 个可用模型
                    </p>
                  )}
                </div>
              </div>
            )}

            <div className="mt-6 flex justify-end">
              <button
                onClick={handleAnalyze}
                disabled={isAnalyzing}
                className="inline-flex items-center px-6 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isAnalyzing ? (
                  <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                ) : (
                  <Users className="h-4 w-4 mr-2" />
                )}
                {isAnalyzing ? '分析中...' : '开始分析'}
              </button>
            </div>
          </div>

          {/* Analysis Result */}
          {analysisResult && (
            <div className="space-y-6">
              {/* Analysis Overview */}
              <div className="bg-white rounded-lg shadow p-6">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-lg font-semibold text-gray-900">分析概述</h2>
                  <button
                    onClick={() => handleCopy(analysisResult.analysis)}
                    className="text-gray-400 hover:text-gray-600"
                    title="复制分析概述"
                  >
                    <Copy className="h-4 w-4" />
                  </button>
                </div>
                <p className="text-gray-700 leading-relaxed whitespace-pre-wrap">
                  {analysisResult.analysis}
                </p>
              </div>

              {/* Primary Personas */}
              {analysisResult.primary_personas && analysisResult.primary_personas.length > 0 && (
                <div className="bg-white rounded-lg shadow p-6">
                  <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                    <Target className="h-5 w-5 mr-2" />
                    主要用户画像
                  </h2>
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    {analysisResult.primary_personas.map(persona =>
                      renderPersonaCard(persona, true)
                    )}
                  </div>
                </div>
              )}

              {/* Potential Personas */}
              {analysisResult.potential_personas &&
                analysisResult.potential_personas.length > 0 && (
                  <div className="bg-white rounded-lg shadow p-6">
                    <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                      <TrendingUp className="h-5 w-5 mr-2" />
                      潜在用户画像
                    </h2>
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                      {analysisResult.potential_personas.map(persona =>
                        renderPersonaCard(persona, false)
                      )}
                    </div>
                  </div>
                )}

              {/* Interest Topics */}
              {analysisResult.interest_topics && analysisResult.interest_topics.length > 0 && (
                <div className="bg-white rounded-lg shadow p-6">
                  <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                    <MessageCircle className="h-5 w-5 mr-2" />
                    感兴趣的话题
                  </h2>
                  {renderInterestTopics(analysisResult.interest_topics)}
                </div>
              )}

              {/* Marketing Strategy */}
              {analysisResult.marketing_strategy && (
                <div className="bg-white rounded-lg shadow p-6">
                  <div className="flex items-center justify-between mb-4">
                    <h2 className="text-lg font-semibold text-gray-900 flex items-center">
                      <BarChart3 className="h-5 w-5 mr-2" />
                      营销策略建议
                    </h2>
                    <button
                      onClick={() => handleCopy(analysisResult.marketing_strategy)}
                      className="text-gray-400 hover:text-gray-600"
                      title="复制营销策略"
                    >
                      <Copy className="h-4 w-4" />
                    </button>
                  </div>
                  <div className="prose max-w-none">
                    <pre className="whitespace-pre-wrap text-gray-700 leading-relaxed">
                      {analysisResult.marketing_strategy}
                    </pre>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* History Tab */}
      {activeTab === 'history' && (
        <div className="space-y-6">
          {/* Filters */}
          <div className="bg-white rounded-lg shadow p-4">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
              <div className="flex items-center space-x-4">
                <input
                  type="text"
                  value={historyFilter.search}
                  onChange={e => setHistoryFilter(prev => ({ ...prev, search: e.target.value }))}
                  className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-900 placeholder-gray-500"
                  placeholder="搜索产品名称..."
                />
                <select
                  value={historyFilter.category}
                  onChange={e => setHistoryFilter(prev => ({ ...prev, category: e.target.value }))}
                  className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-900"
                >
                  <option value="">所有类别</option>
                  <option value="数码电子">数码电子</option>
                  <option value="服装配饰">服装配饰</option>
                  <option value="家居用品">家居用品</option>
                  <option value="美妆护理">美妆护理</option>
                  <option value="食品饮料">食品饮料</option>
                  <option value="其他">其他</option>
                </select>
              </div>
              <button
                onClick={() => fetchHistory(1)}
                className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
              >
                <RefreshCw className="h-4 w-4 mr-2" />
                刷新
              </button>
            </div>
          </div>

          {/* History List */}
          <div className="space-y-6">
            {history.map(item => (
              <div
                key={item.id}
                className="bg-white rounded-lg shadow hover:shadow-md transition-shadow"
              >
                <div className="flex items-start justify-between p-8">
                  <div className="flex-1 cursor-pointer" onClick={() => handleViewDetail(item.id)}>
                    <div className="flex items-center space-x-3 mb-4">
                      <h3 className="text-xl font-semibold text-gray-900 hover:text-blue-600 transition-colors">
                        {item.request.product_name}
                      </h3>
                      {item.request.product_category && (
                        <span className="px-3 py-1 bg-blue-100 text-blue-800 text-sm rounded-full">
                          {item.request.product_category}
                        </span>
                      )}
                      {item.is_favorite && <Heart className="h-5 w-5 text-red-500 fill-current" />}
                    </div>

                    <p className="text-gray-600 text-base mb-4 line-clamp-2 leading-relaxed">
                      {item.request.selling_points}
                    </p>

                    <div className="flex items-center text-sm text-gray-500 mb-2">
                      <Clock className="h-4 w-4 mr-2" />
                      {item.created_at}
                      {item.analysis && (
                        <>
                          <span className="mx-2">•</span>
                          <span>已完成分析</span>
                        </>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center space-x-2 ml-4">
                    <button
                      onClick={e => {
                        e.stopPropagation();
                        handleViewDetail(item.id);
                      }}
                      className="p-2 text-gray-400 hover:text-blue-500"
                      title="查看详情"
                      disabled={loadingDetail}
                    >
                      <Eye className="h-4 w-4" />
                    </button>
                    <button
                      onClick={e => {
                        e.stopPropagation();
                        handleToggleFavorite(item.id);
                      }}
                      className="p-2 text-gray-400 hover:text-red-500"
                      title={item.is_favorite ? '取消收藏' : '收藏'}
                    >
                      <Heart
                        className={`h-4 w-4 ${item.is_favorite ? 'text-red-500 fill-current' : ''}`}
                      />
                    </button>
                    <button
                      onClick={e => {
                        e.stopPropagation();
                        handleDeleteHistory(item.id);
                      }}
                      className="p-2 text-gray-400 hover:text-red-500"
                      title="删除"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </div>

                {/* Show analysis summary if available */}
                {item.analysis && (
                  <div className="mt-6 p-4 bg-gray-50 rounded-lg">
                    <p className="text-sm text-gray-700 line-clamp-3 leading-relaxed">
                      {item.analysis}
                    </p>
                  </div>
                )}

                {/* Show persona count if available */}
                {((item.primary_personas?.length || 0) > 0 ||
                  (item.potential_personas?.length || 0) > 0) && (
                  <div className="mt-4 flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-gray-500">
                    {(item.primary_personas?.length || 0) > 0 && (
                      <div className="flex items-center space-x-1">
                        <Target className="h-4 w-4" />
                        <span>主要用户画像: {item.primary_personas?.length || 0}个</span>
                      </div>
                    )}
                    {(item.potential_personas?.length || 0) > 0 && (
                      <div className="flex items-center space-x-1">
                        <TrendingUp className="h-4 w-4" />
                        <span>潜在用户画像: {item.potential_personas?.length || 0}个</span>
                      </div>
                    )}
                    {(item.interest_topics?.length || 0) > 0 && (
                      <div className="flex items-center space-x-1">
                        <MessageCircle className="h-4 w-4" />
                        <span>兴趣话题: {item.interest_topics?.length || 0}个</span>
                      </div>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between">
              <p className="text-sm text-gray-700">
                显示 {(currentPage - 1) * itemsPerPage + 1} 到{' '}
                {Math.min(currentPage * itemsPerPage, totalItems)} 条， 共 {totalItems} 条记录
              </p>
              <div className="flex items-center space-x-2">
                <button
                  onClick={() => fetchHistory(currentPage - 1)}
                  disabled={currentPage <= 1}
                  className="px-3 py-1 border border-gray-300 rounded text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  上一页
                </button>
                <span className="text-sm text-gray-700">
                  {currentPage} / {totalPages}
                </span>
                <button
                  onClick={() => fetchHistory(currentPage + 1)}
                  disabled={currentPage >= totalPages}
                  className="px-3 py-1 border border-gray-300 rounded text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  下一页
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Detail Modal */}
      {showDetailModal && selectedHistoryItem && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-hidden">
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200">
              <h2 className="text-xl font-semibold text-gray-900">用户画像分析详情</h2>
              <button
                onClick={handleCloseDetailModal}
                className="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            {/* Modal Content */}
            <div className="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
              {/* Product Information */}
              <div className="mb-6">
                <h3 className="text-lg font-semibold text-gray-900 mb-3">产品信息</h3>
                <div className="bg-gray-50 rounded-lg p-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <span className="font-medium text-gray-700">产品名称:</span>
                      <span className="ml-2 text-gray-900">
                        {selectedHistoryItem.request.product_name}
                      </span>
                    </div>
                    {selectedHistoryItem.request.product_category && (
                      <div>
                        <span className="font-medium text-gray-700">产品类别:</span>
                        <span className="ml-2 text-gray-900">
                          {selectedHistoryItem.request.product_category}
                        </span>
                      </div>
                    )}
                    {selectedHistoryItem.request.price_range && (
                      <div>
                        <span className="font-medium text-gray-700">价格区间:</span>
                        <span className="ml-2 text-gray-900">
                          {selectedHistoryItem.request.price_range}
                        </span>
                      </div>
                    )}
                    {selectedHistoryItem.request.target_market && (
                      <div>
                        <span className="font-medium text-gray-700">目标市场:</span>
                        <span className="ml-2 text-gray-900">
                          {selectedHistoryItem.request.target_market}
                        </span>
                      </div>
                    )}
                  </div>
                  <div className="mt-4">
                    <div className="mb-2">
                      <span className="font-medium text-gray-700">产品卖点:</span>
                    </div>
                    <p className="text-gray-900 leading-relaxed">
                      {selectedHistoryItem.request.selling_points}
                    </p>
                  </div>
                  {selectedHistoryItem.request.additional_info && (
                    <div className="mt-4">
                      <div className="mb-2">
                        <span className="font-medium text-gray-700">附加信息:</span>
                      </div>
                      <p className="text-gray-900 leading-relaxed">
                        {selectedHistoryItem.request.additional_info}
                      </p>
                    </div>
                  )}
                </div>
              </div>

              {/* Analysis Results */}
              {selectedHistoryItem.analysis && (
                <div className="space-y-6">
                  {/* Analysis Overview */}
                  <div>
                    <div className="flex items-center justify-between mb-3">
                      <h3 className="text-lg font-semibold text-gray-900">分析概述</h3>
                      <button
                        onClick={() => handleCopy(selectedHistoryItem.analysis || '')}
                        className="text-gray-400 hover:text-gray-600"
                        title="复制分析概述"
                      >
                        <Copy className="h-4 w-4" />
                      </button>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-4">
                      <p className="text-gray-700 leading-relaxed whitespace-pre-wrap">
                        {selectedHistoryItem.analysis}
                      </p>
                    </div>
                  </div>

                  {/* Primary Personas */}
                  {selectedHistoryItem.primary_personas &&
                    selectedHistoryItem.primary_personas.length > 0 && (
                      <div>
                        <h3 className="text-lg font-semibold text-gray-900 mb-3 flex items-center">
                          <Target className="h-5 w-5 mr-2" />
                          主要用户画像
                        </h3>
                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                          {selectedHistoryItem.primary_personas.map(persona =>
                            renderPersonaCard(persona, true)
                          )}
                        </div>
                      </div>
                    )}

                  {/* Potential Personas */}
                  {selectedHistoryItem.potential_personas &&
                    selectedHistoryItem.potential_personas.length > 0 && (
                      <div>
                        <h3 className="text-lg font-semibold text-gray-900 mb-3 flex items-center">
                          <TrendingUp className="h-5 w-5 mr-2" />
                          潜在用户画像
                        </h3>
                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                          {selectedHistoryItem.potential_personas.map(persona =>
                            renderPersonaCard(persona, false)
                          )}
                        </div>
                      </div>
                    )}

                  {/* Interest Topics */}
                  {selectedHistoryItem.interest_topics &&
                    selectedHistoryItem.interest_topics.length > 0 && (
                      <div>
                        <h3 className="text-lg font-semibold text-gray-900 mb-3 flex items-center">
                          <MessageCircle className="h-5 w-5 mr-2" />
                          感兴趣的话题
                        </h3>
                        {renderInterestTopics(selectedHistoryItem.interest_topics)}
                      </div>
                    )}

                  {/* Marketing Strategy */}
                  {selectedHistoryItem.marketing_strategy && (
                    <div>
                      <div className="flex items-center justify-between mb-3">
                        <h3 className="text-lg font-semibold text-gray-900 flex items-center">
                          <BarChart3 className="h-5 w-5 mr-2" />
                          营销策略建议
                        </h3>
                        <button
                          onClick={() => handleCopy(selectedHistoryItem.marketing_strategy || '')}
                          className="text-gray-400 hover:text-gray-600"
                          title="复制营销策略"
                        >
                          <Copy className="h-4 w-4" />
                        </button>
                      </div>
                      <div className="bg-gray-50 rounded-lg p-4">
                        <pre className="whitespace-pre-wrap text-gray-700 leading-relaxed">
                          {selectedHistoryItem.marketing_strategy}
                        </pre>
                      </div>
                    </div>
                  )}
                </div>
              )}

              {!selectedHistoryItem.analysis && (
                <div className="text-center py-8">
                  <div className="text-gray-500">该记录暂无分析结果</div>
                </div>
              )}
            </div>

            {/* Modal Footer */}
            <div className="flex items-center justify-end px-6 py-3 border-t border-gray-200 bg-gray-50">
              <div className="text-sm text-gray-500 mr-4">
                创建时间: {selectedHistoryItem.created_at}
              </div>
              <button
                onClick={handleCloseDetailModal}
                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default UserPersonaAnalysis;
